//
//  CaretakerSettingsController.m
//  Seizure
//
// Caretaker Settings

#import "CaretakerSettingsController.h"
#import "DataManager.h"

@implementation CaretakerSettingsController

@synthesize addPatientInstruction;
@synthesize acceptPatientInstruction;
@synthesize patientStatusLabel;
@synthesize patientNameLabel;
@synthesize patientEmailLabel;
@synthesize inputField;
@synthesize hasAssociatedPatient;
@synthesize addPatientButton;
@synthesize confirmPatientButton;

@synthesize currentPatientEmail;

NSString *lastUpdate = @"lastUpdated";
NSString *waitingConfirmation = @"waitingForResponse";
NSString *waitingFor = @"accountPending";

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"Settings" image:nil tag:1];
        
    }
    return self;
}

/**
 * State dependent method. 
 * If hasAssociatedPatient = YES, then the button will be "Remove"
 * If hasAssociatedPatient = NO, then the button will be "Add"
 */
- (IBAction)patientRequest:(id)sender
{
    DataManager *dm = [DataManager sharedInstance];
    
    //If there is an associated Patient, remove it.
    if( hasAssociatedPatient )
    {
        BOOL result = [dm removePatientCaretakerConnection:dm.user emailToDisconnect:currentPatientEmail];
        if( result )
        {
            [self updatePatientConnectionLabel:@"" name:@""];
        }
    }
    //There was no associated Patient, so we'll try to add the Patient Email from the text field
    else
    {
        NSString *errorMessage = [dm createPatientCaretakerConnection:dm.user emailOfRequested:inputField.text];
        
        //No error -- connection was created between caretaker and patient
        if( errorMessage.length == 0 )
        {
            LinkedAccount *patient = [dm fetchPatient];
            [self updatePatientConnectionLabel:patient.email name:patient.name];
        }
        //
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Unsuccessful" message:errorMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
            [alert show];
        }
    }

}

- (BOOL) textFieldShouldReturn: (UITextField *) textField{
    //Go to the next field if they hit return
    [textField resignFirstResponder];
    
    return YES;
}

/**
 *  When the background is touch, get rid of keyboard.
 */
- (IBAction) backgroundTouched: (id) sender
{
    [inputField becomeFirstResponder];
    [inputField resignFirstResponder];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void) update
{
    DataManager *dm = [DataManager sharedInstance];
    LinkedAccount *associatedPatient = [dm fetchPatient];
    currentPatientEmail = associatedPatient.email;

    [self updatePatientConnectionLabel:currentPatientEmail name:associatedPatient.name];
}

/**
 * Updates the label that says who is currently being monitored.
 * newPatientMonitored - either the Name or Email of the currently
 * monitored patient.
 *
 * Makes a call to updateButtonText
 */
- (void)updatePatientConnectionLabel:(NSString *)newPatientMonitoredEmail name:(NSString *)newPatientMonitoredName
{
    if( newPatientMonitoredEmail.length == 0)
    {
        patientStatusLabel.text = @"You currently have no patient.";
        [patientEmailLabel setHidden:YES];
        [patientNameLabel setHidden:YES];
        hasAssociatedPatient = NO;
    }
    else
    {
        LinkedAccount *linked = [[DataManager sharedInstance] fetchPatient];
    
        [patientEmailLabel setHidden:NO];
        [patientNameLabel setHidden:NO];
        patientEmailLabel.text = [NSString stringWithFormat:@"Email: %@",newPatientMonitoredEmail];
        patientNameLabel.text = [NSString stringWithFormat:@"Currently monitoring: %@.",newPatientMonitoredName];
        
        NSString *statusString = @"";
        if( linked.status == STATUS_CONFIRMED )
            statusString = @"Connection successful.";
        else if( linked.status == STATUS_PENDING )
            statusString = @"Pending Patient confirmation.";
        else if( linked.status == STATUS_WAITING )
            statusString = @"Patient is waiting for your confirmation.";
        
        patientStatusLabel.text = statusString;
        hasAssociatedPatient = YES;
    }
    
    [self updateButtonAndTextField];
}

-(void)updateButtonAndTextField
{
    if( hasAssociatedPatient )
    {
        [addPatientButton setTitle:@"Remove Patient" forState:0];
        [inputField setText:@""];
        [inputField setEnabled:NO];
        [inputField setHidden:YES];
        [addPatientInstruction setHidden:YES];
        
        //Enable or disable the Confirm Patient Button
        LinkedAccount *patient = [[DataManager sharedInstance] fetchPatient];
        if( patient.status == STATUS_CONFIRMED || patient.status == STATUS_PENDING )
        {
            [confirmPatientButton setEnabled:NO];
            [confirmPatientButton setHidden:YES];
            [acceptPatientInstruction setHidden:YES];
        }
        else
        {
            [confirmPatientButton setEnabled:YES];
            [confirmPatientButton setHidden:NO];
            [acceptPatientInstruction setHidden:NO];
        }
    }
    else
    {
        [addPatientButton setTitle:@"Add Patient" forState:0];
        [addPatientInstruction setHidden:NO];
        [inputField setEnabled:YES];
        [inputField setHidden:NO];
        [confirmPatientButton setEnabled:NO];
        [confirmPatientButton setHidden:YES];
    }
}
                                    
-(IBAction)patientConfirm:(id)sender
{
    DataManager *dm = [DataManager sharedInstance];
    NSString *caretakerEmail = [[dm.local retrieveAccount] email];
    [dm confirmPatientCaretakerConnection:caretakerEmail];
    [self update];
}


#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self update];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // make sure to save defaults
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
